<template>
  <a-drawer
    title="发放优惠券"
    :visible="visible"
    :destroyOnClose="true"
    :width="1000"
    :body-style="{
      height: 'calc(100% - 110px)',
      boxSizing: 'border-box',
      overflow: 'auto',
    }"
    :maskClosable="true"
    @close="closeModal"
  >
    <a-radio-group v-if="showChange" v-model:value="grant_type" class="mb-24">
      <a-radio-button :value="1">单个发放</a-radio-button>
      <a-radio-button :value="2">批量发放</a-radio-button>
    </a-radio-group>

    <a-form layout="vertical">
      <a-row :wrap="true" :gutter="24">
        <a-col :span="8" v-if="!isBatch">
          <a-form-item
            label="业户名称"
            v-bind="validateInfos.owner_id"
          >
            <TenantComponent
              :ownerId="modelRef.owner_id"
              :allowes="true"
              titleser="选择业户"
              @selectcancel="selectcancel"
              @changeallowes="changeallowes"
              @request="$utils.commonRequest"
            />
          </a-form-item>
        </a-col>
        <a-col :span="8" v-if="isBatch">
          <a-form-item label="类型" v-bind="validateInfos.batchType">
            <a-select
              v-model:value="modelRef.batchType"
              class="w-100p"
              :options="batchTypeOptions"
            ></a-select>
          </a-form-item>
        </a-col>
        <a-col :span="8" v-if="isBatch">
          <a-form-item label="收费标准名称" v-bind="validateInfos.charge_id">
            <a-select
              placeholder="请选择收费标准"
              v-model:value="modelRef.charge_id"
              class="w-100p"
              :options="standardOptions"
              @change="changeCharge"
            ></a-select>
          </a-form-item>
        </a-col>

        <a-col :span="24" v-if="isBatch">
          <a-form-item v-bind="validateInfos.chargeCostList">
            <a-card size="small">
              <template #title>
                <a-row
                  type="flex"
                  align="middle"
                  justify="space-between"
                  class="table-header"
                >
                  <a-col class="form-table-required">
                    绑定列表（{{ $L("租客") }}数: {{ ownerIds.length }}）
                  </a-col>
                  <a-col>
                    <a-space>
                      <a-button @click="selectHouse"> 选择 </a-button>
                    </a-space>
                  </a-col>
                </a-row>
              </template>
              <a-table
                :columns="houseColumns"
                :data-source="modelRef.chargeCostList"
                :pagination="false"
                rowKey="id"
              >
                <template #bodyCell="{ text, record, index, column }">
                  <template v-if="column.key === 'bill_cost_type'">
                  <span
                  >{{ record.bill_cost_type.bigName }} /{{
                      record.bill_cost_type.name
                    }}
                  </span>
                  </template>
                  <template v-if="column.key === 'action'">
                    <a-button type="link" @click="bindVisible = true"
                    >查看绑定{{ bind_object == 1 ? "房间" : "车位" }}</a-button
                    >
                  </template>
                </template>
              </a-table>
            </a-card>
          </a-form-item>
        </a-col>

        <a-col :span="24">
          <a-form-item v-bind="validateInfos.coupon_list">
            <a-card size="small">
              <template #title>
                <a-row
                  type="flex"
                  align="middle"
                  justify="space-between"
                  class="table-header"
                >
                  <a-col class="form-table-required"> 优惠券列表 </a-col>
                  <a-col>
                    <a-space>
                      <a-button @click="selectCoupon"> 选择优惠券 </a-button>
                    </a-space>
                  </a-col>
                </a-row>
              </template>
              <a-table
                :columns="couponColumns"
                :data-source="modelRef.coupon_list"
                :pagination="false"
                rowKey="id"
              >
                <template #headerCell="{ title, column }">
                  <template v-if="column.key === 'handle_num'">
                    发放数量
                    <text-tip
                      v-if="grant_type === 2"
                      :tips="`发放给${BLCOMMON.utils.L(
                        '租客'
                      )}的优惠劵数量不能大于平均数=剩余优惠劵总数/${BLCOMMON.utils.L(
                        '租客'
                      )}数`"
                    />
                  </template>
                </template>
                <template #bodyCell="{ text, record, index, column }">
                  <template v-if="column.key === 'handle_num'">
                    <a-input-number
                      placeholder="请输入"
                      v-model:value="record.handle_num"
                      :min="1"
                      :max="
                        record.num
                          ? grant_type == 2 && ownerIds.length
                            ? parseInt(
                                (record.num - (record?.received_num || 0)) /
                                  ownerIds.length
                              )
                            : record.num - (record?.received_num || 0)
                          : Infinity
                      "
                      :precision="0"
                      class="w-100p"
                    />
                  </template>
                  <template v-if="column.key === 'action'">
                    <a-popconfirm
                      v-if="modelRef.coupon_list.length"
                      title="是否确定要移除?"
                      @confirm="onDelete(record.id)"
                    >
                      <a>移除</a>
                    </a-popconfirm>
                  </template>
                </template>
              </a-table>
            </a-card>
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
    <div class="drawer-footer">
      <a-button class="mr-10" @click.prevent="closeModal">取消</a-button>
      <a-button
        type="primary"
        :loading="submitLoading"
        @click.prevent="onSubmit"
        >确定</a-button
      >
    </div>

    <!-- 选择房源列表  -->
    <SelectHouseList
      :visible="houseListVisible"
      :id="modelRef.charge_id"
      :rows="modelRef.chargeCostList"
      @closeModal="houseListVisible = false"
      @submitSelect="handleHouseSubmit"
    />

    <!--  选择优惠券列表  -->
    <SelectCouponList
      :visible="couponListVisible"
      :rows="modelRef.coupon_list"
      :grantType="grant_type"
      :ownerNum="ownerIds.length"
      @closeModal="couponListVisible = false"
      @submitSelect="handleCouponSubmit"
    />

    <roomList
      :bindObject="bind_object"
      :visible="bindVisible"
      @close="bindVisible = false"
      :orderInfo="modelRef.chargeCostList[0]"
      :showBill="false"
    />
  </a-drawer>
</template>

<script>
import {
  computed,
  defineComponent,
  reactive,
  ref,
  toRaw,
  toRefs,
  watch,
} from "vue";
import { Form, message } from "ant-design-vue";
import request from "@/common/utils/request";
import { CalendarOutlined, SearchOutlined } from "@ant-design/icons-vue";
import { TextTip , TenantComponent} from "bl-common-vue3";
import store from "@/store";
const useForm = Form.useForm;
import _ from "lodash";
import SelectHouseList from "@/views/bill/CouponManagement/modules/SelectHouseList.vue";
import SelectCouponList from "@/views/bill/CouponManagement/modules/SelectCouponList.vue";
import BLCOMMON from "bl-common-vue3";
import roomList from "@/views/bill/ChargingStandards/modules/roomList.vue";

export default defineComponent({
  name: "IssueCoupon",
  components: {
    SearchOutlined,
    CalendarOutlined,
    TextTip,
    SelectHouseList,
    SelectCouponList,
    roomList,
    TenantComponent
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    // 是否显示切换按钮 收款弹框中不需要切换
    showChange: {
      type: Boolean,
      default: true,
    },
    ownerInfo:{
      type: Object,
      default: ()=>{
        return {}
      },
    }
  },
  setup(props, { emit }) {
    const state = reactive({
      couponColumns: COUPON_COLUMNS,
      grant_type: 1,
      batchTypeOptions: BATCH_TYPE_OPTIONS,
      standardOptions: [],
      houseColumns: HOUSE_COLUMNS,
      houseListVisible: false,
      couponListVisible: false,
      ownerList: [],
      bind_object: 0,
      bindVisible: false,
      submitLoading: false,
    });

    // 表单字段
    const modelRef = reactive({
      owner_id: undefined, // 租客名称
      coupon_list: [],
      batchType: 0, // 批量-类型
      charge_id: undefined,
      chargeCostList: [],
    });

    const ownerIds = computed(() => modelRef.chargeCostList[0]?.ownerIds || []);
    const required = [{ required: true, message: "必填项" }];
    const isBatch = computed(() => state.grant_type === 2);

    const rulesRef = computed(() => {
      return state.grant_type === 1
        ? {
            owner_id: required,
            coupon_list: required,
          }
        : {
            batchType: required,
            charge_id: required,
            chargeCostList: required,
            coupon_list: required,
          };
    });

    // 创建表单
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );
    // 选择优惠券
    const selectCoupon = () => {
      if (state.grant_type === 2 && !modelRef.chargeCostList.length) {
        message.warn("请先选择绑定列表");
        return;
      }
      state.couponListVisible = true;
    };

    // 选择房源
    const selectHouse = () => {
      if (!modelRef.charge_id) {
        message.warn("请先选择收费标准");
        return;
      }
      state.houseListVisible = true;
    };

    const onDelete = (id) => {
      modelRef.coupon_list = modelRef.coupon_list.filter(
        (item) => item.id !== id
      );
    };

    // 提交
    const onSubmit = () => {
      validate().then(() => {
        // 判断发放数量
        let everyGrant = modelRef.coupon_list.every((v) => v.handle_num > 0);
        if (!everyGrant) {
          message.warn("请完善优惠券发放数量后重新提交");
          return;
        }
        state.submitLoading = true;
        let params = {
          grant_type: state.grant_type,
          coupon_list: modelRef.coupon_list,
        };
        if (state.grant_type === 1) {
          // 单个发放
          params.owner_id = modelRef.owner_id;
        } else {
          // 批量发放(目前只有收费标准逻辑)
          params.charge_id = modelRef.charge_id;
          params.chargeCostList = modelRef.chargeCostList;
          params.ownerIds = ownerIds.value;
        }
        request
          .post("/org", "/coupon/giveHandle", { ...params })
          .then((res) => {
            state.submitLoading = false;
            if (res?.error_msg) {
              message.warn(res.error_msg);
            } else {
              message.success("发劵成功");
              emit("successGrant");
            }
          })
          .catch(() => {
            state.submitLoading = false;
          });
      });
    };

    // 切换收费标准
    const changeCharge = (value, option) => {
      state.bind_object = option.bind_object;
      modelRef.chargeCostList = [];
      modelRef.coupon_list = [];
    };

    /**
     * @description: 触发关闭
     */
    const closeModal = () => {
      emit("closeModal");
    };

    // 选择房源 保存
    const handleHouseSubmit = (rows) => {
      if (rows[0].id !== modelRef.chargeCostList[0]?.id) {
        modelRef.coupon_list = [];
      }
      modelRef.chargeCostList = [_.cloneDeep(rows[0])];
      state.houseListVisible = false;
    };

    // 选择优惠券 保存
    const handleCouponSubmit = (rows) => {
      modelRef.coupon_list = _.cloneDeep(rows);
      state.couponListVisible = false;
    };

    const getStandardOptions = () => {
      request.get("/org", "/coupon/getChargeList").then((res) => {
        state.standardOptions = res?.list.map((v) => {
          return {
            value: v.id,
            label: v.name,
            ...v,
          };
        });
      });
    };

    let timeout = null;
    let currentSearchValue = "";
    const getOwnerList = (value, callback) => {
      if (timeout) {
        clearTimeout(timeout);
        timeout = null;
      }
      currentSearchValue = value;
      const getResult = () => {
        request
          .get("/org", "/org/getOwnerList", {
            keywords: value,
          })
          .then((res) => {
            if (currentSearchValue === value) {
              let result = [];
              if (res.list) {
                result = res.list.map((item) => ({
                  value: item.id,
                  label: item.name,
                }));
              }
              callback(result);
            }
          });
      };
      timeout = setTimeout(getResult, 600);
    };

    const onOwnerSearch = (value) => {
      getOwnerList(value, (result) => {
        state.ownerList = result;
      });
    };

    /**
     * @description: 初始化
     */
    const init = () => {
      onOwnerSearch();
      getStandardOptions();
      if(props.ownerInfo.id) {
        modelRef.owner_id = props.ownerInfo.id
      }
    };

    const resetData = () => {
      resetFields();
      state.grant_type = 1;
      state.bind_object = 0;
      state.submitLoading = false;
      state.standardOptions = [];
      state.ownerList = [];
    };


    const selectcancel = (id , data) => {
      modelRef.owner_id = id;
      console.log('modelRef.owner_id modelRef.owner_id',modelRef.owner_id);
    }

    const changeallowes = (id , data) => {
      modelRef.owner_id = id;
      console.log('modelRef.owner_id changeallowes',modelRef.owner_id);
    }

    watch(
      () => props.visible,
      (val) => {
        if (val) {
          // 打开时初始化数据
          init();
        } else {
          // 关闭时重置数据
          resetData();
        }
      }
    );
    return {
      ...toRefs(state),
      validateInfos,
      isBatch,
      modelRef,
      BLCOMMON,
      ownerIds,
      closeModal,
      onSubmit,
      selectCoupon,
      selectHouse,
      onDelete,
      handleHouseSubmit,
      handleCouponSubmit,
      onOwnerSearch,
      changeCharge,
      selectcancel,
      changeallowes
    };
  },
});

const COUPON_COLUMNS = [
  {
    title: "优惠券名称",
    dataIndex: "name",
    key: "name",
    width: "20%",
  },
  {
    title: "绑定项目",
    dataIndex: "village_name",
    key: "village_name",
    width: "20%",
  },
  {
    title: "优惠券金额",
    dataIndex: "amount",
    key: "amount",
    customRender: ({ text, record, index }) => {
      return record.attribute == 1
        ? `￥${record.amount}`
        : record.attribute == 2
        ? `${record.amount}折`
        : "--";
    },
    width: "15%",
  },
  {
    title: "已领数量",
    dataIndex: "received_num",
    key: "received_num",
    width: "15%",
    customRender: ({ text, record, index }) => {
      return text || 0;
    },
  },
  {
    dataIndex: "handle_num",
    key: "handle_num",
    width: "20%",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: "10%",
    fixed: "right",
  },
];

const BATCH_TYPE_OPTIONS = [
  {
    value: 0,
    label: "收费标准",
  },
];

const HOUSE_COLUMNS = [
  {
    title: "费用类型",
    dataIndex: "bill_cost_type",
    key: "bill_cost_type",
    width: "20%",
  },
  {
    title: "绑定日期",
    dataIndex: "created_at",
    key: "created_at",
    width: "20%",
  },
  {
    title: "账单开始时间",
    dataIndex: "start_date",
    key: "start_date",
    width: "15%",
  },
  {
    title: "账单结束时间",
    dataIndex: "end_date",
    key: "end_date",
    width: "15%",
  },
  {
    title: "绑定项目",
    dataIndex: "village_name",
    key: "village_name",
    width: "15%",
  },
  {
    title: "操作",
    dataIndex: "id",
    key: "action",
    width: "15%",
    fixed: "right",
  },
];
</script>

<style lang="less" scoped>
.mb-24 {
  margin-bottom: 24px;
}
.form-table-required:before {
  content: "*";
  color: red;
  margin-right: 4px;
}
:deep(.ant-table-tbody > tr:last-child > td) {
  border-bottom: none !important;
}
:deep(.ant-table-placeholder) {
  border-bottom: none !important;
}
</style>
